package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ITravelCommentRepository travelCommentRepository;

    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {
        //判断类型
        int type = comment.getType();
        if(type==1) {
            TravelComment refTravelComment = travelCommentRepository.findById(comment.getRefComment().getId()).get();
            comment.setRefComment(refTravelComment);
        }
        travelCommentRepository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        Query query=new Query();

        //条件
        query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        //两查
        long count = mongoTemplate.count(query, TravelComment.class);
        //附加条件  分页 排序
        Sort createTime = Sort.by(Sort.Direction.ASC, "createTime");
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(createTime);
        query.with(pageRequest);
        List<TravelComment> travelComments = mongoTemplate.find(query, TravelComment.class);

        return new PageImpl(travelComments,pageRequest,count);
    }

    @Override
    public Long getCountByTravelId(Long travelId) {
        Query query=new Query();
        Query query1 = query.addCriteria(Criteria.where("travelId").is(travelId));
        return mongoTemplate.count(query1,TravelComment.class);
    }
}
